package tech.dubbo.trigger.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.Map;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/10/5
 */
public class MapDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return; // 检查是否有足够的字节来读取
        }

        byteBuf.markReaderIndex();
        int length = byteBuf.readInt(); // 读取数据长度

        if (byteBuf.readableBytes() < length) {
            byteBuf.resetReaderIndex();
            return; // 等待更多的数据
        }

        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);

        // 将字节数组反序列化为 Map
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        Map<String, Object> map = (Map<String, Object>) objectInputStream.readObject();
        out.add(map);
    }
}
